package com.erp.servlet;

import com.erp.bean.Inventory;
import com.erp.bean.Order;
import com.erp.service.InventoryService;
import com.erp.service.OrderService;
import com.erp.service.impl.InventoryServiceImpl;
import com.erp.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author lyb
 * 创建出库控制器
 */
@WebServlet("/returnbatch.action")
public class ReturnBatchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建订单业务逻辑对象
        OrderService orderService = new OrderServiceImpl();
        //创建库存逻辑对象
        InventoryService inventoryService = new InventoryServiceImpl();
        //获取页面传递的库房id


        String ids = req.getParameter("ids");
        String[] id = ids.split(",");

        orderService.updateBatch(11, id);
        for (int i = 0; i < id.length; i++) {
            System.out.println(id[i]);
            Order order = orderService.findById(id[i]);
            int gid = order.getGid();
            int num = order.getCount();
            List<Inventory> inventory = inventoryService.findByGid(gid);
            if (inventory == null) {
                //存入提示信息
                req.setAttribute("ms","您出库的商品缺货请发起采购");
                req.getRequestDispatcher("returnlist.jsp").forward(req,resp);
            } else {
               p: for (Inventory inn:inventory){
                    num=num-inn.getNum();
                    inn.setNum(0);
                    inventoryService.update(inn);
                    if (num<=0){
                        inn.setNum(0-num);
                        inventoryService.update(inn);
                        break p;
                    }
                }

            }
        }
        //重定向到库存列表控制器
        resp.sendRedirect("inventoryall.action");
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
